package model

import business.Attackable
import business.AutoFlyable
import business.Destroyable
import business.Sufferable
import ext.checkCollision
import org.itheima.kotlin.game.core.Painter

/**
 * created by lucus on 2019/4/17
 * e-mail: mcphilex1989@gmail.com
 * phone: 15652608401
 */
class Bullet(
    override val owner: IView,
    override val mCurrentDirection: Direction,
    create: (width: Int, height: Int) -> Pair<Int, Int>
) : AutoFlyable,
    Destroyable, Attackable, Sufferable {


    override val blood: Int = 1
    override val attackBlood: Int = 1
    private var isDestroyed: Boolean = false
    override val speed: Int = 8
    override var x: Int = 0
    override var y: Int = 0
    override val width: Int
    override val height: Int
    private val imgPath = when (mCurrentDirection) {
        Direction.UP -> "/img/shot_top.gif"
        Direction.DOWN -> "/img/shot_bottom.gif"
        Direction.LEFT -> "/img/shot_left.gif"
        Direction.RIGHT -> "/img/shot_right.gif"
    }

    init {
        val size = Painter.size(imgPath)
        width = size[0]
        height = size[1]
        val pair = create.invoke(width, height)
        x = pair.first
        y = pair.second
    }


    override fun draw() {
        Painter.drawImage(imgPath, x, y)
    }

    override fun autoFly() {
        when (mCurrentDirection) {
            Direction.UP -> y -= speed
            Direction.DOWN -> y += speed
            Direction.LEFT -> x -= speed
            Direction.RIGHT -> x += speed
        }
    }

    override fun isDestroy(): Boolean {
        if (isDestroyed) return true

        if (x < -width) {
            return true
        }
        if (x > BaseConfig.GAME_WINDOW_WIDTH) {
            return true
        }
        if (y < -height) {
            return true
        }
        if (y > BaseConfig.GAME_WINDOW_HEIGHT) {
            return true
        }

        return false
    }

    override fun isCollision(sufferable: Sufferable): Boolean {
        return checkCollision(sufferable)
    }

    override fun notifyAttack() {
        // 销毁子弹
        isDestroyed = true
    }

    override fun notifySuffer(attackable: Attackable): Array<IView>? {
        return arrayOf(Blast(x, y))
    }

}